package com.zmn.plat.admin.controller.product;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import com.zmn.common.dto2.ResponseDTO;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dictionary.GlobalDict;
import com.zmn.common.dto.KvDTO;
import com.zmn.common.dto.ResultDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.logger.LoggerUtil;
import com.zmn.common.utils.response.ResponseUtil;
import com.zmn.plat.admin.controller.PlatBaseController;
import com.zmn.plat.business.interfaces.pic.PicUploadBService;
import com.zmn.plat.business.interfaces.product.ServProductBService;
import com.zmn.plat.manager.dictionary.ProductDict;
import com.zmn.plat.model.entity.product.ServProduct;
import com.zmn.plat.model.entity.servcategory.ServAssCategoryQuery;
import com.zmn.plat.model.vo.mast.ImageReslutDTO;
import com.zmn.plat.model.vo.product.ServProductDescVO;
import com.zmn.plat.model.vo.servcategory.ServAssCategoryVO;
import com.zmn.plat.services.interfaces.category.BaseCategoryAttributeEnumService;
import com.zmn.plat.services.interfaces.category.BaseCategoryService;
import com.zmn.plat.services.interfaces.channel.ChannelService;
import com.zmn.plat.services.interfaces.extension.serv.category.group.ExtensionServCategoryGroupService;
import com.zmn.plat.services.interfaces.product.FicoCategoryService;
import com.zmn.plat.services.interfaces.product.ServProductService;
import com.zmn.plat.services.interfaces.product.ServSubsidiaryGroupService;
import com.zmn.plat.services.interfaces.servcategory.ServAssCategoryService;
import com.zmn.plat.services.interfaces.servcategory.ServCategoryService;

/**
 * 描述: 产品管理baseContoller
 *
 * @author tanghongjun
 * @since: 2018/11/5 22:06
 */
public class ServProductBaseController extends PlatBaseController {

    @Resource
    protected ServProductService servProductService;

    @Resource
    protected ServProductBService servProductBService;

    @Resource
    protected BaseCategoryAttributeEnumService baseCategoryAttributeEnumService;

    @Resource
    protected ServCategoryService servCategoryService;

    @Resource
    protected BaseCategoryService baseCategoryService;

    @Resource
    protected ChannelService channelService;

    @Resource
    protected ServAssCategoryService servAssCategoryService;

    @Resource
    protected ServSubsidiaryGroupService servSubsidiaryGroupService;

    @Resource
    protected ExtensionServCategoryGroupService extensionServCategoryGroupService;

    @Resource
    protected FicoCategoryService ficoCategoryService;

    @Resource
    protected PicUploadBService picUploadBService;

    /**
     * 描述: 文件上传 （图片上传 为master模块提供文件上传）
     *
     * @param file
     *            文件对象
     * @param directory
     *            文件地址
     * @param elemId
     *            元素id
     * @param timestamp
     *            师傅id
     * @return com.zmn.common.dto.ImageUploadDTO
     * @author wangjie
     * @since 2018/10/22 10:56
     */
    @SuppressWarnings("Duplicates")
    protected ImageReslutDTO uploaderImage(MultipartFile file, String directory, String elemId, String timestamp) {
        ImageReslutDTO imageReslutDTO = new ImageReslutDTO();
        ImageReslutDTO.Data data = new ImageReslutDTO.Data();
        try {
            directory += timestamp + "/";
            String name = ((CommonsMultipartFile)file).getFileItem().getName();
            int index = name.lastIndexOf(".");
            if (index == -1) {
                return null;
            }
            String suffix = name.substring(index);
            StringBuilder fileName = new StringBuilder(elemId).append(suffix);

            ResultDTO resultDTO = picUploadBService.uploadPic(directory, fileName.toString(), file.getInputStream());
            if (resultDTO.getStatusBool()) {
                imageReslutDTO.setCode(GlobalDict.RESULT_SUCCESS);
                imageReslutDTO.setMsg(GlobalConsts.SUCCESS_MSG);
                data.setSrc(picUploadBService.getPicUrl(directory, fileName.toString()));
                imageReslutDTO.setData(data);
            }
            return imageReslutDTO;
        } catch (Exception e) {
            LoggerUtil.error(this.getClass(), e.getMessage(), e);
            return new ImageReslutDTO(GlobalDict.RESULT_FAIL, "文件上传失败", null);
        }
    }

    /**
     * 功能描述 ： 添加/修改产品描述
     *
     * @param userName
     * @param servProductDescVO
     * @return com.zmn.common.dto2.ResponseDTO
     * @author tanbiao
     * @modifier
     * @since 2019/10/15
     */
    ResponseDTO addEdit(String userName, ServProductDescVO servProductDescVO) {
        if (servProductDescVO.getProductId() == 0) {
            return ResponseDTO.fail("产品ID不正确！");
        }

        ServProduct servProduct = servProductService.findByKey(servProductDescVO.getProductId());
        if (servProduct == null) {
            servProduct = new ServProduct();
        }
        servProduct.setProductDesc(servProductDescVO.getProductDesc());
        servProduct.setUpdater(userName);
        Date now = DateUtil.getNow();
        servProduct.setUpdateTime(now);
        servProductService.updateByKey(servProduct);

        return ResponseDTO.success(true,"操作成功！");
    }

    /**
     * 描述: 分类联动（服务分类查询一级产品分类）showType 为null时则默认为 ProductDict.ERP_PRODUCT_TYPE
     *
     * @param response
     *            响应
     * @param serviceCategoryId
     *            服务分类id
     * @param showType
     *            前台产品,后台产品标识 1后端 2 前端
     * @author wangjie
     * @since 2019/10/15
     **/
    void loadListChilds(HttpServletResponse response, Integer serviceCategoryId, Integer showType) {

        if (serviceCategoryId <= 0) {
            ResponseUtil.outWrite(response, "[]");
            return;
        }
        ServAssCategoryQuery build =
            ServAssCategoryQuery.builder().servCategId(serviceCategoryId).categOneStatus(GlobalConsts.YES).showType(Objects.isNull(showType) ? ProductDict.ERP_PRODUCT_TYPE : showType).build();
        List<KvDTO<Integer, String>> items = servAssCategoryService.listCateOneByQuery(build);
        StringBuilder sb = new StringBuilder("[");
        String jsonFormat = "[\"%s\",\"%s\"]%s ";

        for (int i = 0; i < items.size(); i++) {
            KvDTO<Integer, String> item = items.get(i);
            sb.append(String.format(jsonFormat, item.getKey(), item.getValue(), (i == items.size() - 1 ? "" : ",")));
        }
        sb.append("]");

        ResponseUtil.outWrite(response, sb.toString());
    }

    /**
     * 描述: 分类联动(根据一级产品分类ID和服务类型ID查询二级产品分类) showType 为null时则默认为 ProductDict.ERP_PRODUCT_TYPE
     *
     * @param categOneId
     *            一级产品分类ID
     * @param servCategId
     *            服务分类ID
     * @param showType
     *            前台产品,后台产品标识 1后端 2 前端
     * @author wangjie
     * @since 2019/10/15
     **/
    @SuppressWarnings("Duplicates")
    void loadListCateChilds(HttpServletResponse response, Integer categOneId, Integer servCategId, Integer showType) {

        if (servCategId == ProductDict.ZERO || categOneId == ProductDict.ZERO) {
            ResponseUtil.outWrite(response, "[]");
            return;
        }
        ServAssCategoryQuery query = new ServAssCategoryQuery();
        query.setCategOneId(categOneId);
        query.setServCategId(servCategId);
        query.setCategTwoStatus(GlobalConsts.YES);
        query.setShowType(Objects.isNull(showType) ? ProductDict.ERP_PRODUCT_TYPE : showType);
        List<ServAssCategoryVO> items = servAssCategoryService.listByQuery(query);
        StringBuilder sb = new StringBuilder("[");
        String jsonFormat = "[\"%s\",\"%s\"]%s ";
        ServAssCategoryVO item;
        String name;
        for (int i = 0; i < items.size(); i++) {
            item = items.get(i);
            name = item.getCategName();
            sb.append(String.format(jsonFormat, items.get(i).getCategId(), name, (i == items.size() - 1 ? "" : ",")));
        }
        sb.append("]");
        ResponseUtil.outWrite(response, sb.toString());
    }

    ResponseDTO transAddFlagToMessage(Integer flag) {
        if (flag.equals(ProductDict.FLAG_SUCCESS)) {
            return ResponseDTO.success(true,"新增产品成功！");
        } else if (flag.equals(ProductDict.FLAG_TAFIFF_NAME_ERROR)) {
            return ResponseDTO.fail("新增产品失败，计价器名称不能重复！");
        } else if (flag.equals(ProductDict.FLAG_ATTR_ERROR)) {
            return ResponseDTO.fail("新增产品失败，产品属性组合不能重复！");
        } else if (flag.equals(ProductDict.FLAG_CHANNEL_PRODUCT_NAME_SAME_AS_PRODUCT_NAME_ERROR)) {
            return ResponseDTO.fail("新增失败，渠道产品名称与通用产品名称不能重复！");
        } else if (flag.equals(ProductDict.FLAG_CHANNEL_PRODUCT_NAME_ERROR)) {
            return ResponseDTO.fail("新增失败，同一个渠道下的渠道产品名称不能重复！");
        } else if (flag.equals(ProductDict.FLAG_DEFAULT_PRODUCT_EXIST_ERROR)) {
            return ResponseDTO.fail("新增失败，当前服务分类和产品分类下已经存在默认产品！");
        } else {
            return ResponseDTO.fail("新增失败，产品名称不能重复！");
        }
    }

    ResponseDTO transModifyFlagToMessage(Integer flag) {
        if (flag.equals(ProductDict.FLAG_SUCCESS)) {
            return ResponseDTO.success(true, "修改产品成功！");
        } else if (flag.equals(ProductDict.FLAG_ATTR_ERROR)) {
            return ResponseDTO.fail("修改产品失败，产品属性组合不能重复！");
        } else if (flag.equals(ProductDict.FLAG_TAFIFF_NAME_ERROR)) {
            return ResponseDTO.fail("修改产品失败，计价器名称不能重复！");
        } else if (flag.equals(ProductDict.FLAG_CHANNEL_PRODUCT_NAME_SAME_AS_PRODUCT_NAME_ERROR)) {
            return ResponseDTO.fail("修改产品失败，渠道产品名称与通用产品名称不能重复！");
        } else if (flag.equals(ProductDict.FLAG_CHANNEL_PRODUCT_NAME_ERROR)) {
            return ResponseDTO.fail("修改产品失败，同一个渠道下的渠道产品名称不能重复！");
        } else if (flag.equals(ProductDict.FLAG_DEFAULT_PRODUCT_EXIST_ERROR)) {
            return ResponseDTO.fail("修改产品失败，当前服务分类和产品分类下已经存在默认产品！");
        } else {
            return ResponseDTO.fail("修改产品失败，产品名称不能重复！");
        }
    }

}
